<template>
	<view class="container">
		<scroll-view scroll-y="true" class="form-container">
			<view class="card">
				<text class="section-title">报修信息</text>

				<!-- 报修位置（合并为一行） -->
				<view class="form-item form-item-row">
					<view class="label-row">
						<text class="required">*</text>
						<text class="label">报修位置</text>
					</view>
					<view class="row-select-group">
						<!-- 楼栋选择 -->
						<view class="custom-select" @click="showAddressDropdown = !showAddressDropdown">
							<text class="select-placeholder" v-if="!formData.repair_address">选择楼栋</text>
							<text v-else>
								{{ addressOptions.find(a => a.value === formData.repair_address)?.text }}
							</text>
							<view class="arrow-area">
								<text class="arrow">&#9660;</text>
							</view>
							<!-- 下拉菜单 -->
							<view v-if="showAddressDropdown" class="dropdown-list" @click.stop>
								<view v-for="item in addressOptions" :key="item.value" class="dropdown-item"
									@click="selectAddress(item)">
									{{ item.text }}
								</view>
							</view>
						</view>
						<!-- 房间选择 -->
						<view class="custom-select" @click="showRoomDropdown = !showRoomDropdown">
							<text class="select-placeholder" v-if="!formData.detail_address">详细地点</text>
							<text v-else>
								{{ roomOptions.find(r => r.value === formData.detail_address)?.text }}
							</text>
							<view class="arrow-area">
								<text class="arrow">&#9660;</text>
							</view>
							<!-- 下拉菜单 -->
							<view v-if="showRoomDropdown" class="dropdown-list" @click.stop>
								<view v-for="item in roomOptions" :key="item.value" class="dropdown-item"
									@click="selectRoom(item.value)">
									<view v-if="item.parent == adress?.id">
										{{ item.text }}
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				<!-- 维修类型 -->
				<view class="form-item">
					<view class="label-row">
						<text class="required">*</text>
						<text class="label">报修类型</text>
					</view>
					<view class="custom-select" @click="showRepairTypeDropdown = !showRepairTypeDropdown">
						<text class="select-placeholder" v-if="!formData.repair_type">请选择维修类型</text>
						<text v-else>
							{{ repairTypeOptions.find(t => t.value === formData.repair_type)?.text }}
						</text>
						<view class="arrow-area">
							<text class="arrow">&#9660;</text>
						</view>
						<!-- 下拉菜单 -->
						<view v-if="showRepairTypeDropdown" class="dropdown-list" @click.stop>
							<view v-for="item in repairTypeOptions" :key="item.value" class="dropdown-item"
								@click="selectRepairType(item.value)">
								{{ item.text }}
							</view>
						</view>
					</view>
				</view>

				<!-- 问题描述 -->
				<view class="form-item">
					<view class="label-row">
						<text class="required">*</text>
						<text class="label">报修详情</text>
					</view>
					<textarea
						v-model="formData.repair_content"
						placeholder="请详细描述问题，以便维修人员更好地解决。ps:若地点模糊请在此详细描述"
						class="textarea textarea-blue"
						:auto-height="false"
						rows="4"
					/>
				</view>

				<!-- 图片上传 -->
				<view class="form-item">
					<text class="label">相关图片上传</text>
					<view class="upload-area">
						<view v-for="(img, index) in images" :key="index" class="image-preview">
						  <image :src="img" class="preview-image" mode="aspectFill" />
						  <view class="delete-btn" @click.stop="removeImage(index)">×</view>
						</view>
						<view class="upload-btn-single" @click="chooseImage">
							<image src="/static/scan-icon.png" class="upload-icon" mode="aspectFit" />
							<text class="upload-text">上传图片</text>
						</view>
					</view>
				</view>
			</view>

			<view class="card">
				<text class="section-title">提交人信息</text>
				<!-- 姓名 -->
				<view class="form-item">
					<text class="label">姓名<text class="required">*</text></text>
					<input v-model="formData.sub_name" placeholder="请输入姓名" class="input" />
				</view>
				<!-- 电话 -->
				<view class="form-item">
					<text class="label">电话<text class="required">*</text></text>
					<input v-model="formData.sub_tel" placeholder="请输入联系电话" class="input" type="number" />
				</view>
			</view>

			<!-- 提交按钮 -->
			<button class="submit-btn" @click="submitForm">提交报修单</button>
		</scroll-view>
		<!-- 状态提示 -->
		<uni-popup ref="popup" type="message">
			<uni-popup-message :type="popupType" :message="popupMessage" :duration="2000"></uni-popup-message>
		</uni-popup>
		
		<!-- 补充信息 -->
		<view class="info-section">
			<view class="info-title">
				<text>维修服务说明：</text>
			</view>
			<view class="info-content">
				<text>1. 工作时间：周一至周五 9:00-18:00</text>
				<text>2. 紧急故障请直接拨打：400-888-8888</text>
				<text>3. 提交后可在"我的报修"中查看进度</text>
			</view>
		</view>
		<CustomBottomNav></CustomBottomNav>
	</view>
</template>

<script lang="ts" setup>
	// @ts-ignore
	declare const uni : any;
	// @ts-ignore
	declare function getApp() : any;

	import { ref, reactive, onMounted } from 'vue';
	import { onLoad } from '@dcloudio/uni-app';
	import CustomBottomNav from '../../common/tabar.vue';
	import {usePublicStore} from '../../../store/public'

	const app = getApp();
	const userInfo =usePublicStore();

	// 表单数据结构
	interface RepairForm {
		repair_school : string;
		repair_address : string;
		detail_address : string;
		repair_type : string;
		repair_level : string;
		repair_content : string;
		repair_info : string;
		repair_photo1 : string;
		repair_photo2 : string;
		repair_photo3 : string;
		repair_photo4 : string;
		yuyin_url : string;
		sub_name : string;
		sub_tel : string;
		status : number;
		sub_date ?: Date;
	}

	// 表单数据
	const formData = reactive<RepairForm>({
		repair_school: '',
		repair_address: '',
		detail_address: '',
		repair_type: '',
		repair_level: '1', // 默认普通
		repair_content: '',
		repair_info: '',
		repair_photo1: '',
		repair_photo2: '',
		repair_photo3: '',
		repair_photo4: '',
		yuyin_url: '',
		sub_name: '',
		sub_tel: '',
		status: 0, // 默认未接单状态
	});

	// 图片上传
	const images = ref<string[]>([]);
	const isRecording = ref(false);
	const audioDuration = ref(0);
	const popup = ref();
	const popupType = ref('success');
	const popupMessage = ref('');
	const adress = ref();

	// 选项数据
	const schoolOptions = ref([
		{ value: 'campus1', text: '东校区' },
		{ value: 'campus2', text: '西校区' },
		{ value: 'campus3', text: '南校区' }
	]);

	const addressOptions = ref();

	const repairTypeOptions = ref([
		{ value: '水电维修', text: '水电维修' },
		{ value: '家具维修', text: '家具维修' },
		{ value: '电器维修', text: '电器维修' },
		{ value: '网络维修', text: '网络维修' },
		{ value: '其他维修', text: '其他维修' }
	]);

	const repairLevelOptions = ref([
		{ value: '普通', text: '普通' },
		{ value: '加急', text: '加急' }
	]);

	// 房间号选项
	const roomOptions = ref();

	// 校区选择
	const onSchoolChange = (e : any) => {
		const index = e.detail.value;
		formData.repair_school = schoolOptions.value[index].value;
	};

	// 地址选择
	const showAddressDropdown = ref(false);
	const selectAddress = (value : any) => {
		formData.repair_address = value.value;
		adress.value = value
		showAddressDropdown.value = false;
	};

	// 房间选择
	const showRoomDropdown = ref(false);
	const selectRoom = (value : string) => {
		formData.detail_address = value;
		showRoomDropdown.value = false;
	};

	// 维修类型选择
	const showRepairTypeDropdown = ref(false);
	const selectRepairType = (value : string) => {
		formData.repair_type = value;
		showRepairTypeDropdown.value = false;
	};

	// 维修等级选择
	const onRepairLevelChange = (e : any) => {
		formData.repair_level = e.detail.value;
	};

	// 选择图片
	const chooseImage = () => {
		uni.chooseImage({
			count: 4 - images.value.length,
			sizeType: ['compressed'],
			sourceType: ['album'],
			success: (res) => {
				const tempFilePaths = res.tempFilePaths;
				console.log(tempFilePaths)
				images.value = [...images.value, ...tempFilePaths];

			}
		});
	};

	// 移除图片
	const removeImage = (index : number) => {
		images.value.splice(index, 1);

		// // 重置图片字段
		// for (let i = 1; i <= 4; i++) {
		//   formData[`repair_photo${i}` as keyof RepairForm] = '';
		// }


	};

	// 开始录音
	const startRecord = () => {
		isRecording.value = true;
		audioDuration.value = 0;

		const timer = setInterval(() => {
			if (isRecording.value) {
				audioDuration.value++;
			} else {
				clearInterval(timer);
			}
		}, 1000);

		uni.startRecord({
			success: (res) => {
				formData.yuyin_url = res.tempFilePath;
			},
			fail: (err) => {
				console.error('录音失败:', err);
				showPopup('error', '录音失败，请重试');
			}
		});
	};

	// 停止录音
	const stopRecord = () => {
		isRecording.value = false;
		uni.stopRecord();
	};

	// 播放录音
	const playAudio = () => {
		if (formData.yuyin_url) {
			uni.playVoice({
				filePath: formData.yuyin_url
			});
		}
	};

	// 显示提示
	const showPopup = (type : string, message : string) => {
		popupType.value = type;
		popupMessage.value = message;
		
	};

	// 表单验证
	const validateForm = () : boolean => {

		if (!formData.repair_address) {
			showPopup('error', '请选择地址');
			return false;
		}

		if (!formData.detail_address) {
			showPopup('error', '请输入详细地址');
			return false;
		}

		if (!formData.repair_type) {
			showPopup('error', '请选择维修类型');
			return false;
		}

		if (!formData.repair_content) {
			showPopup('error', '请输入问题描述');
			return false;
		}

		if (!formData.sub_name) {
			showPopup('error', '请输入姓名');
			return false;
		}

		if (!formData.sub_tel) {
			showPopup('error', '请输入联系电话');
			return false;
		}

		if (formData.sub_tel && !/^1[3-9]\d{9}$/.test(formData.sub_tel)) {
			showPopup('error', '手机号格式不正确');
			return false;
		}

		return true;
	};

	const submitForm = async () => {
	  if (!validateForm()) return;
	
	  const baseUrl = getApp().globalData.baseUrl;
	
	  // 1. 先上传图片到 MinIO
	  uni.showLoading({ title: '图片上传中...', mask: true });
	
	  const uploadPromises = images.value.map((localPath) => {
	    return new Promise<string>((resolve, reject) => {
	      uni.uploadFile({
	        url: `${baseUrl}/repair/upload`, // 你的 SpringBoot 地址
	        filePath: localPath,
			header:{
				'X-Tenant-Id': uni.getStorageSync('tenantId'),
				token: uni.getStorageSync('token')
			},
	        name: 'file',
	        success: (res) => {
	          const { data } = JSON.parse(res.data);
	          resolve(data);            // 返回 MinIO 外链
	        },
	        fail: reject
	      });
	    });
	  });
	
	  try {
	    const photoUrls = await Promise.all(uploadPromises);
	    // 依次写入 repair_photo1~4
	    formData.repair_photo1 = photoUrls[0] || '';
	    formData.repair_photo2 = photoUrls[1] || '';
	    formData.repair_photo3 = photoUrls[2] || '';
	    formData.repair_photo4 = photoUrls[3] || '';
	  } catch (e) {
	    uni.hideLoading();
	    uni.showToast({ title: '图片上传失败', icon: 'none' });
	    return;
	  }
	
	  // 2. 再提交业务数据
	  uni.showLoading({ title: '提交中...', mask: true });
	  formData.repair_school = userInfo.getUserInfo().schoolLocal;
	console.log(formData)
	  uni.request({
	    url: encodeURI(baseUrl + '/repair/insert'),
	    method: 'POST',
	    data: formData,
	    header: {
	      'X-Tenant-Id': uni.getStorageSync('tenantId'),
	      token: uni.getStorageSync('token')
	    },
	    success: (res) => {
	      uni.hideLoading();
	      showPopup('success', '报修单提交成功！');
	      setTimeout(() => uni.reLaunch({ url: '/pages/index/index' }), 3000);
	    },
	    fail: () => {
	      uni.hideLoading();
	      uni.showToast({ title: '提交失败，请重试', icon: 'none' });
	    }
	  });
	};

	// 页面加载时初始化用户信息
	onLoad(() => {
		// 模拟从存储中获取用户信息
		const userInfo = {
			name: '',
			phone: '',

		};

		formData.sub_name = userInfo.name;
		formData.sub_tel = userInfo.phone;

	});
	
	const getData = () => {
		const baseUrl = app.globalData.baseUrl;

		uni.request({
			url: encodeURI(baseUrl + '/laboratory/mySchoolLab'),
			method: 'GET',
			data: {
				"schoolId":userInfo.getUserInfo().schoolLocal
			},
			header: {
				"X-Tenant-Id": uni.getStorageSync("tenantId"),
				"token" : uni.getStorageSync("token")
			},
			success: (res) => {
				addressOptions.value = res.data.data.are,
				roomOptions.value = res.data.data.del
			}
		})
	}
	
	onMounted(()=>{
		getData();
	})
</script>

<style scoped>
	.container {
		display: flex;
		flex-direction: column;
		background: #EFEFEF;
		padding: 20rpx 20rpx 200rpx 20rpx;
	}

	/*卡片页面*/
	.card {
		background-color: white;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.section-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 30rpx;
		display: block;
		position: relative;
		padding-left: 20rpx;
	}

	.section-title::before {
		content: '';
		position: absolute;
		left: 0;
		top: 10rpx;
		height: 36rpx;
		width: 8rpx;
		background-color: #1a6dff;
		border-radius: 4rpx;
	}

	.form-item {
		margin-bottom: 40rpx;
	}

	.label {
		font-size: 32rpx;
		color: #555;
		margin-bottom: 16rpx;
		display: block;
	}

	.required {
		color: #f56c6c;
		margin-left: 6rpx;
	}

	.picker,
	.input,
	.textarea {
		background-color: #f8f9fa;
		border-radius: 12rpx;
		padding: 20rpx 24rpx;
		font-size: 30rpx;
		color: #333;
	}

	.picker {
		height: 88rpx;
		display: flex;
		align-items: center;
	}

	.radio-group {
		display: flex;
		margin-top: 10rpx;
	}

	.radio-label {
		margin-right: 40rpx;
		display: flex;
		align-items: center;
		font-size: 30rpx;
	}

	.textarea {
		height: 180rpx;
		width: 604rpx;
	}

	.image-uploader {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
	}

	.image-preview {
		width: 160rpx;
		height: 160rpx;
		border-radius: 12rpx;
		position: relative;
		overflow: hidden;
	}

	.preview-image {
		width: 100%;
		height: 100%;
	}

	.upload-btn {
		width: 160rpx;
		height: 160rpx;
		border: 2rpx dashed #dcdfe6;
		border-radius: 12rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #f8f9fa;
	}

	.delete-btn {
		position: absolute;
		top: 0;
		right: 0;
		width: 40rpx;
		height: 40rpx;
		background-color: rgba(0, 0, 0, 0.5);
		color: white;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 0 0 0 12rpx;
		font-size: 32rpx;
	}

	.voice-section {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 20rpx 0;
	}

	.voice-btn {
		background-color: #1a6dff;
		color: white;
		width: 300rpx;
		height: 90rpx;
		border-radius: 45rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 32rpx;
		font-weight: 500;
	}

	.voice-btn.recording {
		background-color: #f56c6c;
	}

	.voice-info {
		display: flex;
		align-items: center;
		margin-top: 20rpx;
	}

	.duration {
		font-size: 28rpx;
		color: #666;
		margin-right: 20rpx;
	}

	.submit-btn {
		background: linear-gradient(135deg, #1a6dff, #0d5cd6);
		color: white;
		height: 100rpx;
		border-radius: 50rpx;
		font-size: 36rpx;
		font-weight: bold;
		display: flex;
		justify-content: center;
		align-items: center;
		margin: 30rpx 0;
		box-shadow: 0 8rpx 20rpx rgba(26, 109, 255, 0.3);
	}

	.custom-select {
		background-color: #F8F9FA;
		border-radius: 12rpx;
		padding: 0 24rpx;
		font-size: 30rpx;
		color: #333;
		display: flex;
		align-items: center;
		min-width: 0;
		height: 88rpx;
		border: 1rpx solid #e5e5e5;
		position: relative;
		cursor: pointer;
		flex: 1;
		box-sizing: border-box;
	}

	.select-placeholder {
		color: #bbb;
		font-size: 29rpx;
	}

	.arrow-area {
		margin-left: auto;
		display: flex;
		align-items: center;
		height: 100%;
		cursor: pointer;
	}

	.arrow {
		font-size: 32rpx;
		color: #bbb;
		margin-left: 8rpx;
	}

	.dropdown-list {
		position: absolute;
		left: 0;
		top: 100%;
		width: 100%;
		background: #fff;
		border-radius: 16rpx;
		box-shadow: 0 8rpx 32rpx rgba(0,0,0,0.12);
		margin-top: 8rpx;
		z-index: 1001;
		padding: 0;
		max-height: 400rpx;
		overflow-y: auto;
	}

	.dropdown-item {
		padding: 32rpx 40rpx;
		font-size: 30rpx;
		color: #333;
		text-align: left;
		line-height: 1.2;
	}

	.dropdown-item:active {
		background: #f5f7fa;
	}

	.form-item-row {
		display: flex;
		flex-direction: column;
		margin-bottom: 40rpx;
		width: 100%;
	}

	.row-select-group {
		display: flex;
		flex-direction: row;
		gap: 20rpx;
		width: 100%;
	}

	.select-placeholder {
		color: #bbb;
	}

	.arrow {
		margin-left: 20rpx;
		font-size: 28rpx;
		color: #bbb;
	}

	.dropdown-overlay {
		position: fixed;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		z-index: 1000;
	}

	.dropdown-list {
		position: absolute;
		left: 0;
		right: 0;
		background: #fff;
		border-radius: 16rpx;
		box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.12);
		margin-top: 8rpx;
		padding: 0;
		z-index: 1001;
	}

	.dropdown-item {
		padding: 32rpx 40rpx;
		font-size: 32rpx;
		color: #333;
		text-align: left;
	}

	.dropdown-item:active {
		background: #f5f7fa;
	}

	/*补充信息*/
	.info-section {
		background-color: white;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.info-title {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
		color: #000;
		font-size: 32rpx;
		font-weight: bolder;
	}

	.info-title uni-icons {
		margin-right: 8rpx;
		color: #2979ff;
	}

	.info-content {
		display: flex;
		flex-direction: column;
		gap: 16rpx;
		font-size: 27rpx;
	}

	.info-content text {
		font-size: 27rpx;
		color: #333;
		line-height: 1.5;
	}

	.textarea-blue {
		background: #F8F9FA;
		border: 2rpx solid #e5e5e5;
		border-radius: 12rpx;
		padding: 24rpx;
		font-size: 30rpx;
		color: #333;
		min-height: 120rpx;
		box-sizing: border-box;
		width: 100%;
		outline: none;
		resize: none;
	}

	.textarea-blue::placeholder {
		color: #bbb !important;
		font-size: 29rpx;
	}

	.upload-area {
		display: flex;
		align-items: center;
		margin-top: 10rpx;
	}

	.upload-btn-single {
		width: 180rpx;
		height: 180rpx;
		border: 2rpx dashed #dcdfe6;
		border-radius: 12rpx;
		background: #F8F9FA;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		cursor: pointer;
		transition: border-color 0.2s;
	}

	.upload-icon {
		width: 60rpx;
		height: 60rpx;
		margin-bottom: 12rpx;
		opacity: 0.7;
	}

	.upload-text {
		color: #bbb;
		font-size: 28rpx;
	}

	.label-row {
		display: flex;
		align-items: center;
		margin-bottom: 16rpx;
	}

	.required {
		color: #f56c6c;
		margin-right: 8rpx;
		font-size: 32rpx;
	}
</style>